<?php
/**
 * Created by PhpStorm.
 * User: 4399-0661
 * Date: 15-5-9
 * Time: 下午2:30
 */

namespace Library\database;


class LibBase
{
    /**
     * 连接
     * @var \PDO,\mysqli_driver
     */
    public $link = "";
    public $key = "";

    /**
     * 执行sql返回的结果集对象
     * @var \PDOStatement
     */
    public $res = "";

    /**
     *函数执行过程，使用sql查询的次数
     * @var int
     */
    public $count = 0;

    public function __construct($key = "")
    {
        $this->key = $key;
        $this->connection();
    }

    public function __destruct()
    {
        $this->close();
    }

    public function connection()
    {
        return array();
    }

    public function query()
    {
        return array();
    }

    public function close()
    {

    }

    public function getNumRows()
    {

    }

    public function getInsertId()
    {
        return 0;
    }

    public function getAffectedRows()
    {
        return 0;
    }

    public function getAfterError()
    {
        return array();
    }

    /**
     * log
     * @param $string
     * @return bool
     */
    public function _halt($string)
    {
        return \LibLog::custom($string);
    }


    /**
     * 插入数据
     * @param $tableName
     * @param $datas
     * @param bool $returnID
     * @return bool|int|string
     */
    public function insert($tableName, $datas, $returnID = false)
    {
        if (!$tableName) return $this->_halt("Table \"{$tableName}\" is NULL");
        if ($this->_checkTwoDimArray($datas)) return $this->_halt("Multi insert please method 'multiInsert'");
        $this->_insert($tableName, $datas, $returnID);
        if ($returnID) {
            return $this->getInsertId();
        }
        return true;
    }

    /**
     * 开始事务
     */
    public function translateStart()
    {

    }

    /**
     * 提交事务
     */
    public function translateCommit()
    {

    }

    /**
     * 事务回滚
     */
    public function translateRollBack()
    {

    }

    /**
     * 查询结果集的处理
     */
    public function fetchResult()
    {
        return array();
    }

    /**
     * 批量事务插入数据
     * @param $tableName
     * @param $datas
     * @param $returnID
     * @return bool
     */
    public function multiInsert($tableName, $datas, $returnID = false)
    {
        if (!$datas || !is_array($datas)) return $this->_halt("multi Insert \"{$tableName}\"  DATA IS NULL OR NOT ARRAY");
        $this->translateStart();
        foreach ($datas as $data) {
            $this->_insert($tableName, $data, $returnID);
        }
        $this->translateCommit();
        return true;
    }

    private function _insert($tableName, $data)
    {
        if (!$data || !is_array($data)) return false;
        $fields = implode(",", array_keys($data));
        $this->_filterParams($data);
        $values = implode(",", $data);
        $sql = sprintf("insert into %s (%s) values (%s)", $tableName, $fields, $values);
        $this->res = $this->query($sql);
    }

    /**
     * 修改数据
     * @param $tableName
     * @param $datas
     * @param $cond
     * @return bool
     */
    public function update($tableName, $datas, $cond)
    {
        if (!$tableName) return \LibLog::custom("Table \"{$tableName}\" is NULL");
        if (!$datas || !is_array($datas)) return \LibLog::custom("UPDATE \"{$tableName}\"  DATA IS NULL OR NOT ARRAY");
        $set = "";
        $len = count($datas);
        foreach ($datas as $key => &$data) {
            if (is_string($data)) {
                $set .= "{$key}='{$data}',";
            } else {
                $set .= "{$key}=$data,";
            }
        }
        $set = preg_replace('/,$/', "", $set);
        $this->_filterCond($cond);
        $sql = "update {$tableName} set {$set} where {$cond}";
        $this->query($sql);
        return $this->getAffectedRows();
    }

    /**
     * 删除数据
     * @param $tableName
     * @param $cond
     * @return bool|int
     */
    public function delete($tableName, $cond)
    {
        if (!$tableName) return \LibLog::custom("Table \"{$tableName}\" is NULL");
        $this->_filterCond($cond);
        if (!$cond) return 0;
        $sql = sprintf("delete from %s where %s", $tableName, $cond);
        $this->query($sql);
        return $this->getAffectedRows();
    }

    /**
     * 数据查询
     * @param $tableName
     * @param string $field
     * @param array $cond
     * @param string $orderBy
     * @param int $limit
     * @param int $start
     * @param string $parmaryKey
     * @return array|bool
     */
    public function fetch($tableName, $field = "*", $cond = array(), $orderBy = "", $limit = 0, $start = 0, $parmaryKey = "")
    {
        if (!$tableName) {
            return \LibLog::custom("Table is NULL");
        }
        !$field && $field = "*";
        $sql = sprintf("select %s from %s", $field, $tableName);
        if ($this->_filterCond($cond)) {
            $sql .= " where {$cond}";
        }
        $orderBy && $sql .= " order by {$orderBy}";
        if ($limit) {
            if ($start) {
                $sql .= " limit {$start},{$limit}";
            } else {
                $sql .= " limit {$limit}";
            }
        }
        $this->query($sql);
        $datas = $this->fetchResult($parmaryKey);;
        return $datas;
    }

    /**
     * 只返回一条数据
     * @param $tableName
     * @param string $field
     * @param $cond
     * @return array
     */
    public function select($tableName, $field = "*", $cond = "", $orderBy = "")
    {
        $result = $this->fetch($tableName, $field, $cond, $orderBy);
        if (!$result) return array();
        foreach ($result as $rVal) {
            return $rVal;
        }
    }

    /**
     * 计算数据条数
     * @param $tableName
     * @param $cond
     * @return int
     */
    public function count($tableName, $cond = "")
    {
        $this->_filterCond($cond);
        $result = $this->select($tableName, "count(*) as count", $cond);
        return $result['count'] ?: 0;
    }

    /**
     * 验证数据是否是二维数组
     * @param $datas
     * @return bool
     */
    private function _checkTwoDimArray($datas)
    {
        foreach ($datas as $data) {
            if ($data && is_array($data)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 字符串数据加上引号
     * @param $data
     */
    private function _filterParams(&$data)
    {
        foreach ($data as &$val) {
            if (is_string($val)) {
                $val = "'{$val}'";
            }
        }
    }

    /**
     * 过滤条件函数
     * @param $cond
     * @return string
     */
    private function _filterCond(&$cond)
    {
        if (is_array($cond) && !empty($cond)) {
            $cArr = array();
            foreach ($cond as $cKey => $cVal) {
                if (is_string($cVal)) {
                    $cArr[] = sprintf(" %s='%s'", $cKey, $cVal);
                } else {
                    $cArr[] = sprintf(" %s=%d", $cKey, $cVal);
                }
            }
            $cond = implode(" and ", $cArr);
        }
        return $cond;
    }
} 